package com.ruleengine.executer.impl;

import org.apache.log4j.Logger;

import com.ruleengine.context.IContextProperty;
import com.ruleengine.context.IWorkflowConext;
import com.ruleengine.context.IWorkflowContextConstants;
import com.ruleengine.context.impl.ILockObject;
import com.ruleengine.context.impl.WorkflowLockPool;
import com.ruleengine.endpoint.data.IEndpointData;
import com.ruleengine.executer.InstructionExecuter;
import com.ruleengine.executer.exception.InstructionExecuteException;
import com.ruleengine.frame.IRuleEngineFrameConstants;
import com.ruleengine.frame.callback.IRuleEngineCallback;
import com.ruleengine.instruction.impl.TerminateInstruction;

public class TerminateInstructionExecuter implements
        InstructionExecuter<TerminateInstruction> {
    private static Logger logger = Logger
            .getLogger(TerminateInstructionExecuter.class);

    public boolean execute(IWorkflowConext context, IEndpointData data,
            TerminateInstruction instruction)
            throws InstructionExecuteException {
        // TODO Auto-generated method stub
        // 整个调用完成
        try {
            IContextProperty<String> model = context
                    .getContextProperty(IWorkflowContextConstants.WORKFLOW_EXECUTE_MODEL);
            if (IRuleEngineFrameConstants.EXECUTE_MODEL_BLOCKING.equals(model.getValue())) {
                // 阻塞方法进入框架
                IContextProperty<String> p = context
                        .getContextProperty(IWorkflowContextConstants.WORKFLOW_EXECUTE_ID);
                ILockObject lock = WorkflowLockPool.getInstance().getLock(
                        p.getValue());
                if (lock == null) {
                    // 没有获取到同步锁
                    // 这种情况只有在执行并发任务时，出现异常，但是又没有捕获。那么出现异常的那一路就会提前退出
                    logger.error("can't obtain the synchronize lockObject ");
                } else {
                    // 唤醒等待的请求
                    synchronized (lock) {
                        lock.setWorkflowConext(context);
                        lock.setWorkflowData(data);
                        lock.notifyAll();
                    }
                }
            } else {
                // 非阻塞运行
                IContextProperty<IRuleEngineCallback> p = context
                        .getContextProperty(IWorkflowContextConstants.WORKFLOW_CALLBACK);
                if(context.getExceptionCause()!=null){
                    //执行出现异常
                    p.getValue().onException(context, context.getExceptionCause());
                }else{
                    //执行成功
                    p.getValue().onComplete(context, data);
                }
            }
            //不需要继续执行
            return false;
        } catch (Exception e) {
            throw new InstructionExecuteException(e);
        }
    }

}
